var _ITEM_TABLE 					= "itemTable";
var _CUSTOMER_INDICATOR 			= "customerIndicator";
var _RESERVE_DETAIL_INDICATOR 		= "reserveDetailIndicator";

function validateDetailDateFrom(obj) {
	if(validateDateFormat(obj)){
		var dateFrom 	= document.getElementById("serviceDetailStartDate");
		var dateTo 		= document.getElementById("serviceDetailEndDate");
		var day 		= document.getElementById("day");
		
		if(dateFrom.value != "" && dateTo.value != ""){
			var _day		= calculateBetweenDate(dateFrom.value, dateTo.value);
			if(_day <= 0){
				alert("Please input dateFrom less than dateTo.");
				dateFrom.value = "";
				dateFrom.focus();
			}else{
				day.value	= _day;
				getDetailRoomRate();
				calculateDetailTotalAmount();
			}
		}		
	}
}
function validateDetailDateTo(obj) {
	if(validateDateFormat(obj)){
		var dateFrom 	= document.getElementById("serviceDetailStartDate");
		var dateTo 		= document.getElementById("serviceDetailEndDate");
		var day 		= document.getElementById("day");
		
		if(dateFrom.value != "" && dateTo.value != ""){
			var _day		= calculateBetweenDate(dateFrom.value, dateTo.value);
			if(_day <= 0){
				alert("Please input dateTo more than dateFrom.");
				dateTo.value = "";
				dateTo.focus();
			}else{
				day.value	= _day;
				getDetailRoomRate();
				calculateDetailTotalAmount();
			}
		}
	}
}
function getDetailRoomRate(){
	var groupId		= document.getElementById("groupId");
	var dateFrom	= document.getElementById("serviceDetailStartDate");
	var dateTo		= document.getElementById("serviceDetailEndDate");
	var typeOfRoom	= document.getElementById("typeOfRoomId");
	var roomId		= document.getElementById("roomNo");
	
	if(dateFrom.value == ""){
		return false;
	}else if(dateTo.value == ""){
		return false;
	}else if(typeOfRoom.value == ""){
		return false;
	}else if(roomId.value == ""){
		return false;
	}
    var params		= "groupId=" + groupId.value + "&dateFrom=" + dateFrom.value + "&dateTo=" + dateTo.value;
    params		   += "&typeOfRoomId=" + typeOfRoom.value + "&roomId=" + roomId.value;
    
    document.getElementById(_RESERVE_DETAIL_INDICATOR).style.display = "inline";
    isdnSendRequest("reserveDetail_getDetailRoomRateJSON.action", params , "POST", callbackGetDetailRoomRate);
}

callbackGetDetailRoomRate = function() {
    var ready = req.readyState;
    //  console.debug(ready);
    var jsonObject=null;
    if ( ready == 4 ){
        if(req.status == 200) {
            jsonObject=eval( "("+ req.responseText +")" );
            
			var ratePerRoom 	= document.getElementById("ratePerRoom");
			var dateFrom	 	= document.getElementById("serviceDetailStartDate");
			var dateTo	 		= document.getElementById("serviceDetailEndDate");
			var day	 			= document.getElementById("day");
            if(jsonObject.object.data.errCode < 0){
            	alert(jsonObject.object.data.errMsg);
            	dateTo.value	= genNextDay(dateFrom.value, 1);
            	day.value		= 1;
            }
            
            if(jsonObject.object.data.ratePerRoom){
            	ratePerRoom.value	= jsonObject.object.data.ratePerRoom;
            }else{
            	ratePerRoom.value	= 0.00;
            }

            document.getElementById(_RESERVE_DETAIL_INDICATOR).style.display = "none";
        }
    }
};

function validateDetailTypeOfRoom(){
	var typeOfRoomIdObj		= document.getElementById("typeOfRoomId");
	var typeOfRoomObj		= document.getElementById("typeOfRoom");
	
	typeOfRoomObj.value		= typeOfRoomIdObj.options[typeOfRoomIdObj.selectedIndex].text;
	
	createDetailRoomComboList(typeOfRoomIdObj.value);	
}
function createDetailRoomComboList(typeOfRoom){
    var params		= "typeOfRoomId=" + typeOfRoom;

    //clear combo
    document.getElementById("roomNo").options.length 	= 0;
    
    document.getElementById(_RESERVE_DETAIL_INDICATOR).style.display = "inline";
    isdnSendRequest("reserveDetail_getRoomListJSON.action", params , "POST", callbackCreateDetailRoomComboList);
}
callbackCreateDetailRoomComboList = function() {
    var ready = req.readyState;
    //  console.debug(ready);
    var jsonObject=null;
    if ( ready == 4 ){
        if(req.status == 200) {
            jsonObject=eval( "("+ req.responseText +")" );

            if(jsonObject.object.data['com.appsindy.reserv.bo.Combo']){            	
                var detail  = jsonObject.object.data['com.appsindy.reserv.bo.Combo'];
                var size 	= detail.length;
                var isIE 	= detect_browser();
                var roomNo 	= document.getElementById("roomNo");
                if(size){
                	for(var i = 0; i < size; i ++) {
	                    var newOption 	= window.document.createElement("option");
	                    newOption.value = detail[i].key;
	                    newOption.text 	= detail[i].value;
	                    if(isIE==true)
	                    	roomNo.add(newOption);
	                    else
	                    	roomNo.appendChild(newOption); 
                	}
                }else{
                    var newOption 	= window.document.createElement("option");
                    newOption.value = detail.key;
                    newOption.text 	= detail.value;
                    if(isIE==true)
                    	roomNo.add(newOption);
                    else
                    	roomNo.appendChild(newOption);                	
                }
                getDetailRoomRate();
                calculateDetailTotalAmount();
            }
            document.getElementById(_RESERVE_DETAIL_INDICATOR).style.display = "none";
        }
    }
};
function validateDetailRoomNo(){
	getDetailRoomRate();
	calculateDetailTotalAmount();	
}

function validateDetailRatePerRoom(){
	var obj		= document.getElementById("ratePerRoom");
    var val		= obj.value==''?0:parseFloat(removeCommas(obj.value));
    obj.value	= tryNumberFormatValue(val, true, 2);	
    
	//getDetailRoomRate();
	calculateDetailTotalAmount();	
}

function calculateDetailTotalAmount(){
	var ratePerRoom 		= document.getElementById("ratePerRoom");
	var day 				= document.getElementById("day");
	var totalAmount 		= document.getElementById("totalAmount");
	
	var calRate				= ratePerRoom.value==''?0:parseFloat(removeCommas(ratePerRoom.value));
	var calDay				= day.value==''?0:parseFloat(removeCommas(day.value));
	var calTotal			= calRate * calDay;
	
	totalAmount.value		= tryNumberFormatValue(calTotal, true, 2);
}
/*************************************** Item *****************************************/
function addRowItem(){
    var tblBody         = document.getElementById(_ITEM_TABLE);
    var size            = tblBody.rows.length;
    var newRow          = tblBody.insertRow(-1);
    newRow.height       = "30px";
    newRow.className	= "tBody";

    //ItemId
    var tdItemId	    = document.getElementById("templateItemId");
    
    var newCell;
    var rowIndex        = 0;
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = '<a onclick="delRowItem(this)"><img src="./images/calendar/close.gif" /></a>';
    newCell.setAttribute("align","center");
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = size+1;
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = tdItemId.innerHTML;
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = '<input type="text" name="colItemQty" size="5" maxlength="5" onchange="setDetailItemIndex(this);validateDetailItemQty()" class="iNL" onkeypress="return text_OnKeyPress_NumberOnly();"/>';
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = '<input type="text" name="colUnitPrice" size="7" maxlength="10" onchange="setDetailItemIndex(this);validateDetailUnitPrice()" class="iNR" onkeypress="return text_OnKeyPress_NumberOnlyAndDot();"/>';
    newCell             = newRow.insertCell(rowIndex++);
    newCell.innerHTML   = '<input type="text" name="colTotalAmount" size="7" readonly class="iDR"/>';
    
    _ROW_DETAIL_INDEX	= size;    
    validateDetailItemId();
}

function delRowItem(obj){
    var rowIndex        = obj.parentElement.parentElement.rowIndex-1;
    
    var tblBody         = document.getElementById(_ITEM_TABLE);
    if(confirm('Do you want to delete?')){
        tblBody.deleteRow(rowIndex);
        
        calculateAllItemTotalAmount();
    }
}

var _ROW_DETAIL_INDEX = 0;
function setDetailItemIndex(obj){	
    if(obj){
    	var rowIndex = obj.parentElement.parentElement.rowIndex-1;
    	_ROW_DETAIL_INDEX   = rowIndex;
    }	
}

function getItemPrice(){
	var itemId	= document.getElementsByName("colItemId")[_ROW_DETAIL_INDEX];
	
    var params		= "itemId=" + itemId.value;
    
    document.getElementById(_RESERVE_DETAIL_INDICATOR).style.display = "inline";
    isdnSendRequest("reserveDetail_getItemPriceJSON.action", params , "POST", callbackGetItemPricee);
}

callbackGetItemPricee = function() {
    var ready = req.readyState;
    //  console.debug(ready);
    var jsonObject=null;
    if ( ready == 4 ){
        if(req.status == 200) {
            jsonObject=eval( "("+ req.responseText +")" );
            
        	var itemQty		= document.getElementsByName("colItemQty")[_ROW_DETAIL_INDEX];
        	var unitPrice	= document.getElementsByName("colUnitPrice")[_ROW_DETAIL_INDEX];

        	itemQty.value	= tryNumberFormatValue(jsonObject.object.data.itemQty, true, 0);
        	unitPrice.value	= tryNumberFormatValue(jsonObject.object.data.unitPrice, true, 2);

            document.getElementById(_RESERVE_DETAIL_INDICATOR).style.display = "none";
        }
    }
};

function validateDetailItemId(){
	var obj		= document.getElementsByName("colItemId")[_ROW_DETAIL_INDEX];
	
	getItemPrice();
    
	calculateItemTotalAmount();
}

function validateDetailItemQty(){
	var obj		= document.getElementsByName("colItemQty")[_ROW_DETAIL_INDEX];
    var val		= obj.value==''?0:parseFloat(removeCommas(obj.value));
    obj.value	= tryNumberFormatValue(val, true, 0);
    
	calculateItemTotalAmount();
}
function validateDetailUnitPrice(){	
	var obj		= document.getElementsByName("colUnitPrice")[_ROW_DETAIL_INDEX];
    var val		= obj.value==''?0:parseFloat(removeCommas(obj.value));
    obj.value	= tryNumberFormatValue(val, true, 2);	
    
    calculateItemTotalAmount();
}

function calculateItemTotalAmount(){
	var colItemQty 			= document.getElementsByName("colItemQty")[_ROW_DETAIL_INDEX];
	var colUnitPrice 		= document.getElementsByName("colUnitPrice")[_ROW_DETAIL_INDEX];
	var colTotalAmount 		= document.getElementsByName("colTotalAmount")[_ROW_DETAIL_INDEX];
	
	var calQty				= colItemQty.value==''?0:parseFloat(removeCommas(colItemQty.value));
	var calRate				= colUnitPrice.value==''?0:parseFloat(removeCommas(colUnitPrice.value));
	var calTotal			= calRate * calQty;
	
	colTotalAmount.value	= tryNumberFormatValue(calTotal, true, 2);
	
	calculateAllItemTotalAmount();
}
function calculateAllItemTotalAmount(){
	var grandTotalAmount 	= document.getElementById("grandDetailTotalAmount");
	
	//calculate all totalAmount
    var tblBody             = document.getElementById(_ITEM_TABLE);
    var size                = tblBody.rows.length;
    var total				= 0;
    for(var i=0; i<size; i++){
    	var totalObj 		= document.getElementsByName("colTotalAmount")[i];
    	total			   += totalObj.value==''?0:parseFloat(removeCommas(totalObj.value));
    }
	grandTotalAmount.innerText	= tryNumberFormatValue(total, true, 2);
}

dojo.event.topic.subscribe("/afterLookupCustomer", function(data, key, _text, widget){
    if(key != "undefined" && key != null && key != "") {

	    document.getElementById(_CUSTOMER_INDICATOR).style.display = "inline";
	
	    sendRequest("reserveDetail_getCustomerJSON.action", "customerId=" + key , "POST", callbackLookupCustomer);
	
	    document.getElementById("customerId").value = trim(key + "");
    }
});
callbackLookupCustomer = function() {
    try {
        var ready = req.readyState;
        var jsonObject=null;

        if ( ready == 4 ){
            if(req.status == 200) {
            	//alert(req.responseText);
                jsonObject=eval( "("+ req.responseText +")" );

                var customerAuto    = dojo.widget.byId("customerAuto");
                var customerName    = customerAuto.textInputNode.value;
                var customerId    	= document.getElementById("customerId");
                var customerCode    = document.getElementById("customerCode");
                var telephone       = document.getElementById("telephone");
                var mobile          = document.getElementById("mobile");
                var email			= document.getElementById("email");
                if(jsonObject.object.result == "error") {
                    alert(jsonObject.object.data.entry.string[1]);

                    customerName.textInputNode.value= "";
                    customerCode.value    			= "";
                    telephone.value       			= "";
                    mobile.value          			= "";
                    email.value						= "";
                } else {
                    customerId.value    			= getJSONResult(jsonObject.object.data.customerId);
                    customerCode.value    			= getJSONResult(jsonObject.object.data.customerCode);
                    telephone.value       			= getJSONResult(jsonObject.object.data.telephone);
                    mobile.value          			= getJSONResult(jsonObject.object.data.mobile);
                    email.value						= getJSONResult(jsonObject.object.data.email);
                }
            } else {
                alert("A problem occurred with communicating between the " +
                      "XMLHttpRequest object and the server program. " +
                      "Please try again very soon");
            }
        }
        document.getElementById(_CUSTOMER_INDICATOR).style.display = "none";
    } catch (err) {
        alert("It does not appear that the server " +
          "is available for this application. Please " +
          "try again very soon. \\nError: "+ err.message);
        document.getElementById(_CUSTOMER_INDICATOR).style.display = "none";
    }
};

dojo.event.topic.subscribe("/beforeSaveReserveDetail", function(event, widget){
    try{
        var customerAuto    = dojo.widget.byId("customerAuto");
        var customerName    = customerAuto.textInputNode;        
		var dateFrom 		= document.getElementById("serviceDetailStartDate");
		var dateTo 			= document.getElementById("serviceDetailEndDate");
		var day 			= document.getElementById("day");
		var typeOfRoomId	= document.getElementById("typeOfRoomId");
		var roomNo 			= document.getElementById("roomNo");
		var ratePerRoom 	= document.getElementById("ratePerRoom");		
		var typeOfRoom		= document.getElementById("typeOfRoom");
		
		typeOfRoom.value	= typeOfRoomId.options[typeOfRoomId.selectedIndex].text;
		
        var tblBody         = document.getElementById(_ITEM_TABLE);
        var size            = tblBody.rows.length;

//        if(customerName.value == ""){
//			alert("Please input Customer");
//			customerName.focus();
//			event.cancel = true;
		if(dateFrom.value == ""){
			alert("Please input dateFrom");
			dateFrom.focus();
			event.cancel = true;
		}else if(dateTo.value == ""){
			alert("Please input dateTo");
			dateTo.focus();
			event.cancel = true;
		}else if(day.value == ""){
			alert("Please input day");
			day.focus();
			event.cancel = true;
		}else if(typeOfRoomId.value == ""){
			alert("Please input TypeOfRoom");
			typeOfRoomId.focus();
			event.cancel = true;
		}else if(roomNo.value == ""){
			alert("Please input roomNo");
			roomNo.focus();
			event.cancel = true;
		}else if(ratePerRoom.value == ""){
			alert("Please input ratePerRoom");
			ratePerRoom.focus();
			event.cancel = true;
	    //}else if(size == 0) {
	    //	alert("Please input item per room.");
	    //	event.cancel = true;
	    }else if(!validateItemDetail()){
	    	event.cancel = true;
       	}else{
       		if(!confirm("Do you want to save?")){
       			event.cancel = true;
       		}
       	}
    }catch(err ) {
         alert("Javascript error in this reserve info page beforeSaveReserveDetail main function() [Error: " + err.message + "]");
         event.cancel = true;
    }
});

function validateItemDetail(){
    var tblBody         = document.getElementById(_ITEM_TABLE);
    var size            = tblBody.rows.length;
    
    var msgQtyMorethanZero = document.getElementById("msgQtyMorethanZero").innerText;
    
    var arrItemId		= document.getElementsByName("colItemId");
    var arrItemQty		= document.getElementsByName("colItemQty");
    var arrUnitPrice	= document.getElementsByName("colUnitPrice");
    if(size > 0){
    	var itemTmp = '';
    	for(var i=0; i<size; i++){    		
    		if(arrItemId[i].value == ''){
    			alert("Please input item.");    			
    			arrItemId[i].focus();
    			return false;
    		}else if(arrItemQty[i].value == ''){
    			alert("Please input item qty.");
    			arrItemQty[i].focus();
    			return false;
    		}else if(arrItemQty[i].value != '' && parseInt(arrItemQty[i].value) <= 0){
    			alert(msgQtyMorethanZero);
    			arrItemQty[i].focus();
    			return false;
    		}else if(arrUnitPrice[i].value == ''){
    			alert("Please input unit price.");
    			arrUnitPrice[i].focus();
    			return false;
    		}    		
    		if(itemTmp != '' && itemTmp == arrItemId[i].value){
    			alert("Duplicate item.");
    			arrItemId[i].focus();
    			return false;
    		}
    		itemTmp = arrItemId[i].value;
    	}
    }
    return true;
}

function gotoNewCustomerPopup(){
	var serviceDetailId	= document.getElementById("serviceDetailId").value;
	var groupId			= document.getElementById("groupId").value;
	var params			= "?groupId=" + groupId +"&serviceDetailId=" + (serviceDetailId?serviceDetailId:'0');
	gotoCustomerPopup(params);
}
function gotoEditCustomerPopup(){
	var customerId		= document.getElementById("customerId").value;
	var serviceDetailId	= document.getElementById("serviceDetailId").value;
	var groupId			= document.getElementById("groupId").value;
	var params			= "?customerId=" + customerId + "&groupId=" + groupId + "&serviceDetailId=" + (serviceDetailId?serviceDetailId:'0');
	if(customerId != '' && customerId != '0'){
		gotoCustomerPopup(params);
	}
}

function gotoCustomerPopup(params) {

    var popupHeight = 450;
    var popupWidth = 600;

    var posX = parseInt((window.screen.availWidth - popupWidth) / 2);
    var posY = parseInt((window.screen.availHeight - popupHeight) / 2);

    if (posX < 0) { posX = 0; }
    if (posY < 0) { posY = 0; }

    var url		= "reserveDetail_newCustomer.action";
    
    params		= params==null?'':params;
    var popup 	= window.open(url + params, 'customer', "location=no,menubar=no,resizable=no,status=yes,toolbar=no,width="+ popupWidth +",height="+ popupHeight+",scrollbars=no,left=" + posX + ",top=" + posY , "true");                
    tmp_popup 	= popup;
    return popup;
}
window.focus();
if (!window.opener)
	window.document.write();

var openerObj = window.opener;
function refreshInfoRoom(){
	var opennerForm 						= openerObj.frmReserveInfoRoom;	
	
	var serviceHeaderId						= document.getElementById("serviceHeaderId").value;
	var flagSave							= document.getElementById("flagSave").value;
	opennerForm.serviceHeaderId.value 		= serviceHeaderId;
	opennerForm.groupId.value				= document.getElementById("groupId").value;
	if(serviceHeaderId != '' && parseInt(serviceHeaderId) > 0 && flagSave != '' && flagSave == 'Y'){
		openerObj.refreshReserveInfoRoom();	
		window.close();
	}
}

//for customer call
function refreshReserveDetail(){
	var btnObj = document.getElementById("btnRefreshReserveDetail");
	btnObj.click();
}